<template>
  <!-- 设计图纸管理 -->
  <base-breadcrumb class="allPlan" :breadcrumb="!isAudit">
    <a-spin :spinning="loading">
      <a-row :gutter="24">
        <a-col :span="6" style="border-right: 1px solid #d9d9d9">
          <a-card :bordered="false">
            <title-name title="分类"></title-name>
            <tree-search
              ref="treeSearch"
              :showButton="editModel != 0"
              :replaceFields="{ children: 'children', title: 'groupName', key: 'id' }"
              :id="id"
              :api="api"
              :quote="false"
              emptyDescription="暂无数据"
              :requestArgs="{ basicsStandardId: id, year: year }"
              isAll
              @loader="loader"
              :isDelete="true"
              :autoSelect="false"
              :addDisable="loading"
              :selectedKeys.sync="selectedKeys"
              :selectOptions.sync="selectOptions"
              :form-list="[
                {
                  keyName: 'status',
                  type: 'a-select',
                  span: 24,
                  label: '状态',
                  data: [
                    {
                      label: '启用',
                      value: 0
                    },
                    {
                      label: '禁用',
                      value: 1
                    }
                  ]
                }
              ]"
            />
          </a-card>
        </a-col>
        <a-col :span="18">
          <searchData :searchData="searchArr" @search="search"></searchData>
          <a-card>
            <title-name title="规范清单"></title-name>
            <!-- 表格 -->
            <b-table :page-keys="['pageNum', 'pageSize', 'total']" ref="table" :columns="columns" :request="loadData"
                     :selectConfig="{
                          use: editModel == 0, //是否使用，传false不会显示选择栏
                          type: 'checkbox', //checkbox或radio，多选或者单选
                          rowKey: 'id'
                      }"
                     :rowSelectionConfig="rowSelectionConfig"
            >
              <!-- 新增 -->

              <a-button
                v-if="editModel != 0"
                slot="prefix"
                icon="plus"
                type="primary"
                :disabled="selectedKeys.length == 0 || selectOptions.hasChildren"
                @click="handleManage('2')"
                >新增</a-button
              >
              <a-button
                      v-if="editModel == 0"
                      slot="prefix"
                      type="primary"
                      :disabled="selectedRowKeys.length == 0"
                      @click="exportExcle('1')"
              >导出选中</a-button
              >
              <a-button
                      v-if="editModel == 0"
                      slot="prefix"
                      type="primary"
                      @click="exportExcle('2')"
              >导出全部</a-button
              >
              <span slot="operation" slot-scope="text, record">
                <a @click="handleManage('0', record)">查看</a>
                <!-- 编辑 -->
                <span v-if="editModel != 0">
                  <a-divider type="vertical" />
                  <a @click="handleManage('1', record)">编辑</a>
                </span>
                <!-- 删除 -->
                <span v-if="editModel != 0">
                  <a-divider type="vertical"></a-divider>
                  <a-popconfirm title="确定要删除?" @confirm="() => handleRemove(record, 0)">
                    <a>删除</a>
                  </a-popconfirm>
                </span>
              </span>
            </b-table>
          </a-card>
        </a-col>
      </a-row>
      <div v-if="!isConsultation" class="btn_box page-btn-right-top">
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
    </a-spin>
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      :edit-model="editModelDialog"
      :form="form"
      :header-title="editModelDialog == 'V' ? '查看规范清单' : editModelDialog == 2 ? '新增规范清单' : '编辑规范清单'"
      :width="700"
      :isEmit="false"
      :rules="rules"
      :form-list="formList"
      @confirm="submitForm"
      :clearForm="true"
      :styles="{ width: '450px' }"
    />
  </base-breadcrumb>
</template>
<script>
import { STable } from '@/components' // 表格
import DialogForm from '@/components/DialogForm' // 弹窗
import TreeSearch from '../TreeSearch' // 树
import { technicalStandardDetailedListExport } from '@/api/technology'
import {
  addBasicsStandard,
  getBasicsStandardTreeList,
  addBasicsTree,
  updateBasicsTree,
  delBasicsTree,
  getBasicsTableList,
  addBasicsTable,
  updateBasicsTable,
  delBasicsTable,
  expireTable,
  invalidTable,
  getNodeTree
} from '@/api/technical/specificationList'
import BSelect from '@/components/BComponents/BSelect'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '图集/标准号',
    dataIndex: 'atlasStandardNumber',
    ellipsis: true
  },
  {
    title: '图集名称',
    dataIndex: 'atlasName',
    ellipsis: true
  },
  {
    title: '分类',
    dataIndex: 'groupName',
    ellipsis: true
  },
  {
    title: '类型',
    dataIndex: 'type',
    ellipsis: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    ellipsis: true
  },

  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    width: '180px',
    scopedSlots: { customRender: 'operation' }
  }
]
const searchArr = [
  {
    name: '图集/标准号',
    value: 'atlasStandardNumber',
    type: 'input'
  },
  {
    name: '图集名称',
    value: 'atlasName',
    type: 'input'
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    STable,
    TreeSearch,
    DialogForm
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      selectedKeys: [],
      selectedRowKeys: [],
      selectOptions: {},
      loading: false,
      visible: false, // 弹窗控件
      editModelDialog: '0',
      year: new Date().getFullYear() + '',

      api: {
        getList: getBasicsStandardTreeList,
        create: addBasicsTree,
        update: updateBasicsTree,
        delete: delBasicsTree,
        getDetails: getNodeTree
      },
      form: {
        groupName: ''
      },
      rules: {
        atlasStandardNumber: [{ required: true, message: '请输入' }],
        atlasName: [{ required: true, message: '请输入' }],
        type: [{ required: true, message: '请输入' }],
        remark: [{ required: true, message: '请输入' }]
      },
      queryParam: {},
      loadData: async parameter => {
        this.queryParam.basicsStandardId = this.id
        this.queryParam.groupMenuId = this.selectedKeys.length > 0 ? this.selectOptions.id : void 0
        const requestParameters = Object.assign({}, parameter, { param: this.queryParam })
        return getBasicsTableList(requestParameters).then(res => {
          if (res.code === '0') {
            return {
              code: 200,
              data: res.data.list,
              total: res.data?.total,
              currentPage: res.data?.pageNum
            }
          }
        })
      }
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'groupName',
          type: 'BaseInput',
          label: '所属分类',
          disabled: true,
          span: 24
        },
        {
          keyName: 'atlasStandardNumber',
          type: 'BaseInput',
          label: '图集/标准号',
          span: 24
        },

        {
          keyName: 'atlasName',
          type: 'BaseInput',
          label: '图集名称',
          span: 24
        },
        {
          keyName: 'type',
          type: 'BaseInput',
          label: '类型',
          span: 24
        },
        {
          keyName: 'remark',
          type: 'BaseTextarea',
          label: '备注',
          span: 24
        }
      ]
    },
      rowSelectionConfig(){
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
        }
      }
  },
  mounted() {
    this.$route.meta.title = ['基础规范查看', '基础规范编辑', '基础规范新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.$nextTick(this.$refs.treeSearch?.getList)
    } else {
      this.$nextTick(() => {
        this.addBasicsStandardReq()
        this.init = true
      })
    }
  },
  methods: {
    exportExcle(type) {
      if(type==='1') {
        technicalStandardDetailedListExport({ids: this.selectedRowKeys, ...this.queryParam }).then(res=>{
          this.downLoadExl(res.data)
        })
      } else {
        technicalStandardDetailedListExport(this.queryParam).then(res=>{
            this.downLoadExl(res.data)
        })
      }
    },
    downLoadExl(data){
      const blob = new Blob([data])
      const url = window.URL.createObjectURL(blob)
      const ele = document.createElement("a")
      ele.href = url;
      ele.target="_blank"
      ele.download = '基础规范清单.xlsx'
      document.body.appendChild(ele)
      ele.click()
      document.body.removeChild(ele)
    },
    onSelectChange(selectRowKeys) {
      this.selectedRowKeys = selectRowKeys
    },
    handleRemove(record, type) {
      const api = [delBasicsTable, expireTable, invalidTable][type]
      api({ id: record.id }).then(res => {
        this.$message.success(['删除', '过期', '作废'][type] + '成功!')
        this.$refs.table.refresh(true)
      })
    },
    /**
     * 操作栏 type:0 新增;1 编辑
     */
    handleManage(type, record) {
      this.editModelDialog = type == '0' ? 'V' : type // 映射操作类型
      this.form = type != '2' ? this.$clone(record) : {} // 配置参数

      this.form.groupName = type == '2' ? this.selectOptions?.groupName : this.form.groupName //设置选中分类
      this.visible = true // 打开表单
    },
    /**
     * 表格新增
     */
    submitForm(e) {
      e.basicsStandardId = this.id //主表id
      e.groupMenuId = this.selectOptions?.id //分类id

      const api = [updateBasicsTable, addBasicsTable][this.editModelDialog - 1]
      this.$refs.dialogForm.loading = true
      api(e)
        .then(res => {
          this.$refs.dialogForm.loading = false
          this.visible = false
          this.$message.success(['修改', '新增'][this.editModelDialog - 1] + '成功')
          this.$refs.table.refresh(true)
        })
        .catch(res => {
          this.$refs.dialogForm.loading = false
        })
    },
    loader() {
      console.log(this.selectOptions)

      this.$refs.table.refresh(true)
    },
    //搜索
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    //新增
    addBasicsStandardReq() {
      this.loading = true
      const userInfo = this.$userInfo()
      addBasicsStandard({ year: this.year, branchComId: userInfo.currentPost.orgId })
        .then(res => {
          this.id = res.data.id
          this.loading = false
          this.$nextTick(this.$refs.treeSearch?.getList)
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>
